package com.teen9g.infoplatformserver.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.teen9g.PageQueryDTO.MaimaiChunithmPageQueryDTO;
import com.teen9g.constant.CategoryConstant;
import com.teen9g.constant.MaimaiChunithmConstant;
import com.teen9g.constant.RedisKey;
import com.teen9g.context.BaseContext;
import com.teen9g.dto.MaimaiChunithmDTO;
import com.teen9g.entity.MaimaiChunithm;
import com.teen9g.entity.SingleRecentEdit;
import com.teen9g.infoplatformserver.mapper.MaimaiChunithmMapper;
import com.teen9g.infoplatformserver.mapper.RecentEditMapper;
import com.teen9g.infoplatformserver.service.MaimaiChunithmService;
import com.teen9g.userVO.MaimaiChunithmUserVO;
import com.teen9g.utils.StringUtil;
import com.teen9g.vo.MaimaiChunithmVO;
import org.codehaus.jettison.json.JSONException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class MaimaiChunithmServiceImpl implements MaimaiChunithmService {

    @Autowired
    private MaimaiChunithmMapper maimaiChunithmMapper;

    @Autowired
    private RecentEditMapper recentEditMapper;

    @Autowired
    private RedisTemplate<String, Long> redisTemplate;
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 根据id获取舞萌中二条目
     *
     * @param id 舞萌中二条目id
     * @return 舞萌中二条目
     */
    @Override
    public MaimaiChunithm getById(Integer id) {
        return maimaiChunithmMapper.selectByOne(id);
    }

    @Override
    public PageInfo<MaimaiChunithmVO> page(MaimaiChunithmPageQueryDTO mcpQueryDTO) {
        PageHelper.startPage(mcpQueryDTO.getPageNum(), mcpQueryDTO.getPageSize());
        List<MaimaiChunithmVO> list = maimaiChunithmMapper.selectByPage(mcpQueryDTO);
        return new PageInfo<>(list);
    }

    /**
     * 分页查询舞萌中二条目
     *
     * @param mcpQueryDTO 舞萌中二条目分页查询DTO
     * @return 舞萌中二条目分页信息
     */
    @Override
    public PageInfo<MaimaiChunithmUserVO> pageUser(MaimaiChunithmPageQueryDTO mcpQueryDTO) {
        PageHelper.startPage(mcpQueryDTO.getPageNum(), mcpQueryDTO.getPageSize());
        List<MaimaiChunithmUserVO> list = maimaiChunithmMapper.selectByPageUser(mcpQueryDTO);
        for (MaimaiChunithmUserVO mcuVO : list) {
            if (mcuVO.getContentImage() != null) {
                //提取出图片的第一张用于展示
                try {
                    String[] images = objectMapper.readValue(mcuVO.getContentImage(), String[].class);
                    if (images.length > 0) {
                        mcuVO.setContentImage(images[0]);
                    }
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return new PageInfo<>(list);
    }


    /**
     * 添加舞萌中二条目
     *
     * @param maimaiChunithmDTO 舞萌中二条目DTO
     * @return 舞萌中二条目添加结果
     */
    @Override
    public String add(MaimaiChunithmDTO maimaiChunithmDTO) {
        MaimaiChunithm maimaiChunithm = new MaimaiChunithm();
        BeanUtils.copyProperties(maimaiChunithmDTO, maimaiChunithm);
        maimaiChunithm.setContentAuthor(BaseContext.getCurrentUser());
        maimaiChunithm.setContentRecentEditor(BaseContext.getCurrentUser());
        maimaiChunithm.setContentCreateTime(LocalDateTime.now());
        maimaiChunithm.setContentUpdateTime(LocalDateTime.now());
        int insert = maimaiChunithmMapper.insert(maimaiChunithm);
        if (insert > 0) {
            return MaimaiChunithmConstant.ADD_SUCCESS;
        } else {
            return MaimaiChunithmConstant.ADD_FAILED;
        }
    }

    @Override
    public String update(MaimaiChunithmDTO maimaiChunithmDTO, Integer id) throws JSONException {
        //判断传入的实体是否为空
        if (maimaiChunithmDTO == null) {
            return MaimaiChunithmConstant.UPDATE_EMPTY;
        }
        //判断传入的参数是否为空
        if (id == null) {
            return MaimaiChunithmConstant.UPDATE_ID_EMPTY;
        }
        //判断要更改的实体是否存在
        MaimaiChunithm maimaiChunithm = maimaiChunithmMapper.selectById(id);
        if (maimaiChunithm == null) {
            return MaimaiChunithmConstant.UPDATE_NOT_FOUND;
        }
        //中继DTO
        MaimaiChunithmDTO temp = new MaimaiChunithmDTO();
        BeanUtils.copyProperties(maimaiChunithm, temp);
        //先获取更新了什么内容
        StringUtil stringUtil = new StringUtil();
        String operation = stringUtil.MC_getOperation(maimaiChunithmDTO, temp);
        if (!operation.isEmpty()) {
            //先插入一条编辑记录
            SingleRecentEdit singleRecentEdit = SingleRecentEdit.builder()
                    .updateEditor(BaseContext.getCurrentUser())
                    .updateTime(LocalDateTime.now())
                    .contentCategory(CategoryConstant.MAIMAI_CHUNITHM)
                    .contentId(id)
                    .contentTitle(maimaiChunithmDTO.getShopName())
                    .updateOperation(operation)
                    .build();
            recentEditMapper.insert(singleRecentEdit);
        }
        //更新
        BeanUtils.copyProperties(maimaiChunithmDTO, maimaiChunithm);
        maimaiChunithm.setContentRecentEditor(BaseContext.getCurrentUser());
        maimaiChunithm.setContentUpdateTime(LocalDateTime.now());
        int update = maimaiChunithmMapper.updateById(maimaiChunithm);
        if (update > 0) {
            return MaimaiChunithmConstant.UPDATE_SUCCESS;
        } else {
            return MaimaiChunithmConstant.UPDATE_FAILED;
        }

    }

    @Override
    public String delete(Integer id) {
        //判断是否为作者
        MaimaiChunithm maimaiChunithm = maimaiChunithmMapper.selectById(id);
        if (!maimaiChunithm.getContentAuthor().equals(BaseContext.getCurrentUser())) {
            return MaimaiChunithmConstant.DELETE_NOT_AUTHOR;
        }
        int delete = maimaiChunithmMapper.deleteById(id);
        if (delete > 0) {
            return MaimaiChunithmConstant.DELETE_SUCCESS;
        } else {
            return MaimaiChunithmConstant.DELETE_FAILED;
        }
    }

    @Override
    public void addView(Integer id) {
        redisTemplate.opsForValue().increment(RedisKey.MC_VIEW_KEY + id);
    }


}
